package com.example.tvscreendisplay;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PictureActivity extends FragmentActivity {

    private ImageView imageview;

    private static String url = "http://hdwq.wine-manu.top/prod-api/manu/pubToolScreen/screenInfoById/";

    private SharedPreferences SP;
    private SharedPreferences.Editor editor;

    //异步(**选取Android OS的handler**)
    private Handler mHandler = new Handler(Looper.myLooper()){

        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 100){
                String data = (String) msg.obj;

                //将json数据转为数据实体类(JAVA 对象)
                ScreenInfoDetail screenInfoDetail = new Gson().fromJson(data, ScreenInfoDetail.class);


                if(screenInfoDetail.getCode() == 200 && screenInfoDetail.getData() != null){
                    Glide.with(PictureActivity.this)
                            .load(screenInfoDetail.getData().getUrl())
                            .error(R.drawable.file_error)
                            .into(imageview);
                } else if (screenInfoDetail.getCode() == 500) {

                    //服务器错误（code:500）
                    Glide.with(PictureActivity.this)
                            .load(R.drawable.server_error)
                            .into(imageview);

                } else {

                    //data为空
                    Glide.with(PictureActivity.this)
                            .load(R.drawable.data_null)
                            .into(imageview);
                }


            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture);

        imageview = (ImageView)findViewById(R.id.imageview);
        //imageview添加聚焦
        imageview.requestFocus();

        //实例化对象(SharedPreferences 文件的名称与MainActivity中的SharedPreferences要一致，都为data_storage。否则无法获取Id值)
        SP = getSharedPreferences("data_storage", Context.MODE_PRIVATE);
        editor = SP.edit();

        getHttpDataDetail();

        imageview.setOnClickListener(mOnClickListener);

    }

    private void getHttpDataDetail() {

        //获取MainActivity的点击事件传递过来的数据
        //Intent intent = getIntent();

        String id = SP.getString("Id","");

        if (!id.isEmpty()) {

            //Log.d("----getId----","getId:"+id);

            //创建OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            //构建Request对象
            Request request = new Request.Builder()
                    .url(url+id)
                    .get()
                    .build();
            //通过OkHttpClient对象和Request对象来构建Call对象

            Call call = client.newCall(request);
            //通过Call对象的enqueue（Callback）方法来执行异步请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.d("--------","onFailure:"+e.toString());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                    //Log.d("--------","onResponse:"+response.body().string());

                    String data = response.body().string();

                    //不能直接在这里操作UI，因为这是一个耗时操作，要使用handler
                    Message message = new Message();
                    message.what = 100;
                    message.obj = data;

                    //发送
                    mHandler.sendMessage(message);

                }
            });

        } else {

            Log.d("----Failure----","Failure");

        }

    }

//    public void onImageViewClick(View view) {
//        Toast.makeText(this, "已完成刷新", Toast.LENGTH_SHORT).show();
//    }

    private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int id = view.getId();
            if (id == R.id.imageview) {

                getHttpDataDetail();

                Toast.makeText(PictureActivity.this, "已完成刷新", Toast.LENGTH_LONG).show();

            }

        }
    };

}
